<?php
if(!interface_exists('XPartitionStrategy', false)){
	require(dirname(__FILE__).DIRECTORY_SEPARATOR.'XPartitionStrategy.php');
}
class XHashPartitionStrategy implements XPartitionStrategy{
	public function partition(XAnnotation $annotations, $value){
		if(!is_string($value) && !is_int($value)){
			throw new XORMException("Partition Hash Strategy requires a string partition id.");
		}
		$algorithm = $annotations->get('Strategy.algorithm');		
		if(is_null($algorithm)){
			$algorithm = 'md5';
		}
		$result = strtolower(substr(hash($algorithm, $value), 0, 1));
		$name = $annotations->get('Partition.name');
		if(preg_match('/[a-z0-9]/i', $result)){
			return $name.'_'.$result;
		}
		return $this->partition($annotations, '');
	}
	
	public function allPartitions(XAnnotation $annotations){
		$name = $annotations->get('Partition.name');
		$range = array_merge(range('a', 'z'), range(0, 9));
		$tables = array();
		foreach($range as $value){
			$tables[] = $name.'_'.$value;
		}
		return $tables;
	}
	
	public function totalCount(XAnnotation $annotations){
		return 36;
	}	
}
?>